package com.chao.gulimall.product.exception;


import com.chao.common.exception.BizCodeEnume;
import com.chao.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

//@ResponseBody
//@ControllerAdvice(basePackages="com.chao.gulimall.product.controller")
//@ControllerAdvice(value="com.chao.gulimall.product.controller")

@Slf4j
@RestControllerAdvice(value="com.chao.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleValidaException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型:{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
//        return R.error(10400,"数据校验出现问题").put("data",errorMap);
        return R.error(BizCodeEnume.VAVLID_EXCEPTION.getCode(),BizCodeEnume.VAVLID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable t){
        log.error("异常", t);
        return R.error(BizCodeEnume.UNKNOW_EXEPTION.getCode(),BizCodeEnume.UNKNOW_EXEPTION.getMsg());
    }
}
